package br.com.megasena.file.decompress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.log4j.Logger;

import br.com.megasena.constantes.MegaSenaConstantes;

public class MegaSenaDecompress {

	static Logger log = Logger.getLogger(MegaSenaDecompress.class.getName());

	public static File decompressFile(final File zippedFile) throws Exception {

		ZipInputStream zis = new ZipInputStream(new FileInputStream(zippedFile));
		ZipEntry ze = zis.getNextEntry();
		byte[] buffer = new byte[1024];
		try {
			while (ze != null) {

				if (ze.getName().contains(
						MegaSenaConstantes.FILE_NAME_EXTENSION)) {

					File newFile = new File(
							MegaSenaConstantes.DIR_NAME_RESULTADOS
									+ File.separator + ze.getName());

					log.debug("file unzip : " + newFile.getAbsoluteFile());

					if (newFile.exists()) {
						newFile.delete();
					}

					newFile.createNewFile();
					FileOutputStream fos = new FileOutputStream(newFile);

					int len;
					while ((len = zis.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}

					fos.close();

					return newFile;
				} else {
					ze = zis.getNextEntry();
				}
			}
		} catch (Exception e) {
			return null;
		} finally {
			zis.closeEntry();
			zis.close();

		}
		return null;
	}

}
